package com.star.spring.netty.service;

import java.util.concurrent.ConcurrentHashMap;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;

import org.springframework.stereotype.Service;

@Service
public class DeviceMessageService {
    private final ConcurrentHashMap<String, Channel> deviceChannels = new ConcurrentHashMap<>();

    /**
     * Register a device channel
     *
     * @param deviceId the device identifier
     * @param channel  the Netty channel
     */
    public void registerDevice(String deviceId, Channel channel) {
        deviceChannels.put(deviceId, channel);
    }

    /**
     * Unregister a device channel
     *
     * @param deviceId the device identifier
     */
    public void unregisterDevice(String deviceId) {
        deviceChannels.remove(deviceId);
    }

    /**
     * Send a message to a specific device
     *
     * @param deviceId the device identifier
     * @param message  the message to send
     * @return true if the message was sent successfully, false otherwise
     */
    public boolean sendMessageToDevice(String deviceId, String message) {
        Channel channel = deviceChannels.get(deviceId);
        if (channel != null && channel.isActive()) {
            ChannelFuture future = channel.writeAndFlush(message);
            return future.isSuccess();
        }
        return false;
    }

    /**
     * Broadcast a message to all connected devices
     *
     * @param message the message to broadcast
     */
    public void broadcastMessage(String message) {
        deviceChannels.values().forEach(channel -> {
            if (channel.isActive()) {
                channel.writeAndFlush(message);
            }
        });
    }
}